package com.xinzhi.aspect;

import com.xinzhi.mapper.TLogMapper;
import com.xinzhi.model.po.TLogz;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

@Aspect
@Component
public class ControllerMonitoringAspect {
    @Autowired
    private HttpServletRequest request;

    @Resource
    private TLogMapper tLogMapper;

    @Before("execution(* com.xinzhi.controller.*.*(..))")
    public void beforeControllerMethodExecution(JoinPoint joinPoint) {
        // 目标方法执行前的操作
//        获取ip
        String ipAddress = request.getRemoteAddr();
//        获取方法名
        String methodName = joinPoint.getSignature().getName();
        if (methodName=="sMain1"){
            methodName="审核主页内容";

        }else if (methodName=="sAudit"){
            methodName="预审核内容";

        }else if (methodName=="sUpdateAudit"){
            methodName="预审核修改操作";

        }else if (methodName=="sUpdateRelease"){
            methodName="审核发布撤回";

        }
        //获取参数
        Object[] arguments = joinPoint.getArgs();
        String sa = Arrays.toString(arguments);

        // 从HTTP请求中获取Token
//        String token = request.getHeader("Authorization");

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

// 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// 格式化时间为年月日，详细到秒
        String time = now.format(formatter);
        // 输出请求的IP和参数


        TLogz tLogz = new TLogz();
        tLogz.setId(0);
        tLogz.setIp(ipAddress);
        tLogz.setMethod(methodName);
        tLogz.setTime(time);
        tLogz.setValue(sa);
        tLogMapper.insert(tLogz);
    }

//    @AfterReturning("execution(* com.xinzhi.controller.*.*(..))")
//    public void afterControllerMethodExecution(JoinPoint joinPoint) {
//        // 目标方法执行后的操作
//        String methodName = joinPoint.getSignature().getName();
//        System.out.println("Finished method: " + methodName);
//    }

}